import "./reset.css";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import ReCropperPreview from "@/components/ReCropperPreview";
import type { FormItemProps } from "../utils/types";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection,
  cloneDeep
} from "@pureadmin/utils";
import {
  getUserList,
  create,
  update,
  del,
  getJobTitleListApi
} from "@/api/userApi";
import { updatePassword, updateStatus } from "@/api/userApi";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";

import { getDeptTree } from "@/api/deptApi";
export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧部门树的id
    username: "",
    keyword: "",
    phone: "",
    departmentId: "",
    page: 1,
    perPage: 10
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "登录账号",
      prop: "username"
    },
    {
      label: "昵称",
      prop: "nickname"
    },
    {
      label: "性别",
      prop: "gender",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.gender === 1 ? "danger" : null}
          effect="plain"
        >
          {row.gender === 1 ? "男" : "女"}
        </el-tag>
      )
    },
    {
      label: "部门",
      prop: "department.name"
    },
    {
      label: "手机号码",
      prop: "phone",
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    {
      label: "状态",
      prop: "status",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "入职时间",
      minWidth: 90,
      prop: "entryDate"
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createdAt"
    },
    {
      label: "最后登录时间",
      minWidth: 90,
      prop: "loginTime"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: "",
    confirmPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          updateStatus({
            userId: row.userId,
            status: row.status
          }).then(result => {
            if (result.code === 200) {
              message("已成功修改用户状态", {
                type: "success"
              });
            } else {
              message("修改失败", { type: "error" });
            }
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }

  function handleDelete(row) {
    del({ userId: row.userId }).then(result => {
      if (result.code == 200) {
        message(`删除成功`, { type: "success" });
        onSearch();
      } else {
        message(`删除失败`, { type: "error" });
      }
    });
    onSearch();
  }

  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getUserList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getUserList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const { result } = await getUserList(form);
      dataList.value = result.list;
      pagination.total = result.total;
      pagination.pageSize = result.pageSize;
      pagination.currentPage = result.currentPage;
    } catch (error) {
      message(error.response.data.msg ?? "操作失败,请联系管理员", {
        type: "error"
      });
    }

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.departmentId = "";
    treeRef.value.onTreeReset();
    onSearch();
  };
  function formatHigherDeptOptions(treeList) {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }
  const formInline = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    getJobTitleListApi().then(result => {
      formInline.value.jobTitleIdOptions = result.result;
    });
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
        higherDeptOptions: formatHigherDeptOptions(cloneDeep(treeData.value)),
        username: row?.username ?? "",
        phone: row?.phone ?? "",
        email: row?.email ?? "",
        nickname: row?.nickname ?? "",
        password: row?.password ?? "",
        gender: row?.gender ?? 1,
        status: row?.status ?? 1,
        remarks: row?.remarks ?? "",
        isSuperAdmin: 0,
        roleIds: row?.roleIds ?? []
      };
    } else {
      formInline.value = {
        title: "修改",
        higherDeptOptions: formatHigherDeptOptions(cloneDeep(treeData.value)),
        username: row?.username ?? "",
        userId: row?.userId ?? "",
        phone: row?.phone ?? "",
        email: row?.email ?? "",
        nickname: row?.nickname ?? "",
        gender: row?.gender ?? 1,
        status: row?.status ?? 1,
        remarks: row?.remarks ?? "",
        roleIds: row?.roleIds ?? [],
        jobTitleId: row?.jobTitleId ?? 0,
        isSuperAdmin: row?.isSuperAdmin ?? 0
      };
    }
    if (row?.departmentId != "" && row?.departmentId != undefined) {
      formInline.value.departmentId = row.departmentId;
    }

    addDialog({
      title: `${title}用户`,
      props: {
        formInline: formInline
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.username}的这条数据`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              create(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              update(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: row.avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        done();
        onSearch();
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                },
                {
                  validator: (rule, value, callback) => {
                    if (value.length > 9 || value.length < 6) {
                      callback(new Error("密码长度在6到8个字符之间"));
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
            <ElFormItem
              prop="confirmPwd"
              rules={[
                {
                  validator: (rule, value, callback) => {
                    if (pwdForm.newPwd != value) {
                      callback(new Error("两次密码不一致"));
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.confirmPwd}
                placeholder="确认密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            updatePassword({
              userId: row.userId,
              password: pwdForm.newPwd
            }).then(result => {
              if (result.code === 200) {
                message(`已成功重置 ${row.username} 用户的密码`, {
                  type: "success"
                });
              } else {
                message("重置失败", { type: "error" });
              }
            });
            done();
            onSearch();
          }
        });
      }
    });
  }

  onMounted(async () => {
    treeLoading.value = true;
    await onSearch();
    treeData.value = (await getDeptTree()).result;
    try {
      const { result } = await getUserList().finally(() => {
        treeLoading.value = false;
      });
      roleOptions.value = result.list;
    } catch (e) {}
  });
  function onTreeSelect({ id, selected }) {
    form.departmentId = selected ? id : "";
    onSearch();
  }
  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onTreeSelect,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleUpload,
    handleReset,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
